package com.ktjy.util.filter;


import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class HelloFilter implements Filter {
    //filter 初始化
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter init");
        Filter.super.init(filterConfig);
    }

    //判断是否继续往后面执行，业务逻辑
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter...执行前");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //获取到请求的url
        //http://localhost:8080/ch15/js/common.js
        String servletPath = httpServletRequest.getServletPath();
        //判断请求的url，如果后缀是js,css 直接doFilter,可以直接放行
        if (servletPath.startsWith("/js/") || servletPath.startsWith("/user/login")
                || servletPath.startsWith("/user/doLogin")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            httpServletRequest = (HttpServletRequest) servletRequest;
            Object object = httpServletRequest.getSession().getAttribute("session_user");
            if (object == null) {
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                httpServletResponse.sendRedirect("/ch15/error.jsp");
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }
        System.out.println("doFilter...执行后");
    }

    //销毁
    @Override
    public void destroy() {
        System.out.println("Filter destroy");
        Filter.super.destroy();
    }
}
